﻿// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections;
using System.Data;

namespace SnapObjects.Data.PostgreSql
{
    internal class PostgreSqlColumnSchemaProvider : SqlColumnSchemaProvider
    {
        public PostgreSqlColumnSchemaProvider(DataContext context) : base(context)
        { 
        }

        protected override bool IsExtraHandleNullable => true;

        protected override bool IsReadOnly(DataRow row, IDataReader reader)
        {
            var column = row.Table.Columns["isreadonly"];

            var value = row.ItemArray[column.Ordinal];

            return this.GetSchemaItemValue<bool>(value);
        }

        protected override bool IsIdentity(DataRow row, IDataReader reader)
        {
            var isIdentity = base.IsIdentity(row, reader);

            if (!isIdentity)
            {
                var column = row.Table.Columns["isautoincrement"];

                var value = row.ItemArray[column.Ordinal];

                return this.GetSchemaItemValue<bool>(value);
            }

            return isIdentity;
        }

        protected override Type ColumnDataType(DataRow row, IDataReader reader)
        {
            var type = base.ColumnDataType(row, reader);

            if (type == typeof(BitArray) && this.ColumnSize(row, reader) == 1)
            {
                return typeof(bool);
            }

            return type;
        }

        protected override bool AllowDbNull(DataRow row, IDataReader reader)
        {
            var tableName = this.ColumnTableName(row, reader);

            if (String.IsNullOrWhiteSpace(tableName))
            {
                return true;
            }

            return base.AllowDbNull(row, reader);
        }
    }
}
